package com.cnap.multiclouldmgmt.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cnap.multiclouldmgmt.model.K8sClusterInfoModel;
import com.cnap.multiclouldmgmt.model.RepByPage;
import com.cnap.multiclouldmgmt.model.enums.AlarmLevelEnum;
import com.cnap.multiclouldmgmt.model.enums.K8sRoleEnum;
import com.cnap.multiclouldmgmt.model.enums.MsgTypeEnum;
import com.cnap.multiclouldmgmt.model.gpu.MicroSvcGpuInfoModel;
import com.cnap.multiclouldmgmt.model.gpu.NodeQueryModel;
import com.cnap.multiclouldmgmt.model.k8sModels.*;
import com.cnap.multiclouldmgmt.model.k8sMonitorModels.AlgReqModel;
import com.cnap.multiclouldmgmt.model.k8sMonitorModels.DynamicExpansionSvcAlgModel;
import com.cnap.multiclouldmgmt.model.k8sMonitorModels.K8sClusterAlgInfoModel;
import com.cnap.multiclouldmgmt.model.microSvc.*;
import com.cnap.multiclouldmgmt.model.microSvc.alg.*;
import com.cnap.multiclouldmgmt.model.microSvc.assist.AlarmSvcDataModel;
import com.cnap.multiclouldmgmt.model.microSvc.assist.MsgInfoAssist;
import com.cnap.multiclouldmgmt.model.microSvc.assist.SvcDataModel;
import com.cnap.multiclouldmgmt.model.scale.intelligent.IndicatorEnum;
import com.cnap.multiclouldmgmt.model.scale.intelligent.QueryThresholdParam;
import com.cnap.multiclouldmgmt.model.vm.FlavorResourceModel;
import com.cnap.multiclouldmgmt.repository.cnap.AlarmMapper;
import com.cnap.multiclouldmgmt.repository.cnap.MicroSvcMapper;
import com.cnap.multiclouldmgmt.repository.cnap.MsgCenterInfoMapper;
import com.cnap.multiclouldmgmt.repository.master.MicroSvcUseInfoMapper;
import com.cnap.multiclouldmgmt.service.*;
import com.cnap.multiclouldmgmt.util.CnapCloudMgmtConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;

@Service("MicroSvcInfoServiceImpl")
public class MicroSvcInfoServiceImpl implements MicroSvcInfoService {

    private final static Logger LOGGER = LoggerFactory.getLogger(MicroSvcInfoServiceImpl.class);

    @Autowired
    private CacheService cacheService;

    @Autowired
    private MicroSvcUseInfoMapper microSvcUseInfoMapper;

    @Autowired
    private MicroSvcMapper microSvcMapper;

    @Autowired
    private MsgCenterInfoMapper msgCenterInfoMapper;

    @Autowired
    private K8sClusterService k8sClusterService;

    @Autowired
    private MultiCloudMgmtService multiCloudMgmtService;

    @Autowired
    private AlarmMapper alarmMapper;

    @Autowired
    private AlgInfoService algInfoService;

    @Autowired
    private PrometheusService prometheusService;

    //算法的url
    @Value("${alg.url}")
    private String algUrl;

    @Override
    public void delMsgCenterInfo(int id) {
        msgCenterInfoMapper.delMsgCenterInfo(id);
    }

    @Override
    public RepByPage<MsgInfo> getMsgCenterInfos(String userName, int pageSize, int pageNo) {

        RepByPage<MsgInfo> result = new RepByPage<>();

        result.setPageNo(pageNo);
        result.setPageSize(pageSize);

        result.setTotalNum(msgCenterInfoMapper.countMsgInfoNum(userName));
        result.setResult(new ArrayList<>());

        List<MsgInfoModel> msgInfoModels = msgCenterInfoMapper.getMsgInfosByPage(userName,
                (pageNo - 1) * pageSize,pageSize);
        if ((msgInfoModels != null)&&(!msgInfoModels.isEmpty())){

            for (MsgInfoModel msgInfoModel:msgInfoModels){

                MsgInfo msgInfo = new MsgInfo();
                msgInfo.setId(msgInfoModel.getId());
                msgInfo.setMsgType(msgInfoModel.getMsgType());

                MsgTypeEnum msgTypeEnum = MsgTypeEnum.getMsgTypeEnumByMsgType(msgInfoModel.getMsgType());
                if (msgTypeEnum == null){
                    continue;
                }
                msgInfo.setMsgInfos(new ArrayList<>());
                msgInfo.getMsgInfos().add(new MsgInfoAssist(
                   msgTypeEnum.getMsgItem01(),msgInfoModel.getItem01()));
                msgInfo.getMsgInfos().add(new MsgInfoAssist(
                        msgTypeEnum.getMsgItem02(),msgInfoModel.getItem02()));
                msgInfo.getMsgInfos().add(new MsgInfoAssist(
                        msgTypeEnum.getMsgItem03(),msgInfoModel.getItem03()));
                result.getResult().add(msgInfo);
            }

        }

        return result;
    }

    /**
     * 获取最近的30条
     * @param indicatorId
     * @return
     */
    @Override
    public List<IndicatorHistoryModel> getIndicatorHistoryModels(String indicatorId) {

        //先根据indicatorId查到要查询的svcId和内容
        IndicatorHistoryModel checkModel = microSvcMapper.getIndicatorIdCheckKey(indicatorId);

        int totalNum = microSvcUseInfoMapper.getIndicatorHistoryModelNum(checkModel.getMicroSvcId());

        int pageSize = 30;
        int offset = Math.max(0,(totalNum - pageSize));

        List<IndicatorHistoryModel> indicatorHistoryModels =
                microSvcUseInfoMapper.getIndicatorHistoryModelByPage(checkModel.getMicroSvcId(),
                        offset, pageSize);
        if (!indicatorHistoryModels.isEmpty()) {
            for (IndicatorHistoryModel indicatorHistoryModel : indicatorHistoryModels) {
                indicatorHistoryModel.setIndicatorKey(checkModel.getIndicatorKey());
            }
        }

        return indicatorHistoryModels;
    }

    /**
     * 删除这些应用
     * @param svcName
     * @param k8sClusterName
     * @throws ParseException
     */
    @Override
    public void delMicroSvc(String svcName,String k8sClusterName,String svcId) throws Exception {

        LOGGER.warn("delMicroSvc svcName={} k8sClusterName={} svcId={}",svcName,
                k8sClusterName,svcId);

        K8sClusterBasicModel k8sClusterBasicModel
                = multiCloudMgmtService.getK8sClusterInfoByName(k8sClusterName);
        //找到所有部署了这个svc的node
        List<NodeModel> nodeModels =
                k8sClusterService.getAllNodeInfo(k8sClusterBasicModel,"",
                        CnapCloudMgmtConstants.NODE_APP_LABEL,svcName);

        if ((nodeModels == null)||(nodeModels.isEmpty())){

            LOGGER.warn("delMicroSvc svcName={} nodeModels is empty",svcName);
            return;
        }
        for (NodeModel nodeModel:nodeModels){

            if (StringUtils.equals(nodeModel.getNodeRole(), K8sRoleEnum.Master.getStatus())){

                LOGGER.warn("delMicroSvc svcName={} node={} is master",svcName,nodeModel.getNodeName());

                //把label设置为空
                k8sClusterService.changeNodeLabel(k8sClusterName,nodeModel.getNodeName(),
                        CnapCloudMgmtConstants.NODE_APP_LABEL,CnapCloudMgmtConstants.NODE_APP_LABEL_EMPTY);
                k8sClusterService.delNodeLabel(k8sClusterName,nodeModel.getNodeName(),
                        CnapCloudMgmtConstants.NODE_APP_LABEL_ID);
            }

            if (StringUtils.equals(nodeModel.getNodeRole(),K8sRoleEnum.Slave.getStatus())){

                LOGGER.warn("delMicroSvc svcName={} to del node={}",svcName,nodeModel.getNodeName());

                //删除节点
                k8sClusterService.delK8sClusterNode(k8sClusterBasicModel.getK8sClusterIp(),nodeModel.getNodeName());
            }
        }
    }

    @Override
    public ForececastRiskCpuModel getCpuRishTrends(String microSvcId){
        //如果cpu，那就查cpu使用率，gpu就显示温度

        ForececastRiskCpuModel forececastRiskCpuModel = new ForececastRiskCpuModel();

        String url =  algUrl + "/forecast_risk_cpu";

        //获取用户设置的cpu thresh
        ScalingService scalingService = SpringUtil.getBean(ScalingService.class);
        QueryThresholdParam queryThresholdParam = new QueryThresholdParam();
        queryThresholdParam.setSvcIds(new ArrayList<>());
        queryThresholdParam.getSvcIds().add(microSvcId);
        queryThresholdParam.setIndicatorName(IndicatorEnum.CPU.getName());

        queryThresholdParam.setResType("微服务");
        queryThresholdParam.setNodeNames(new ArrayList<>());

        String cpuThresh = scalingService.getIntelligentThreshold(queryThresholdParam);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("service_id",microSvcId);
        paramMap.put("cpu_thresh",Integer.parseInt(cpuThresh));

        String param = JSON.toJSONString(paramMap);
        try {

            String result = doHttpPostReq(url, new StringEntity(param));
            if (StringUtils.isNotEmpty(result)) {
                LOGGER.error("getCpuRishTrends result microSvcId={} result={}",microSvcId,result);
                forececastRiskCpuModel
                        = JSONObject.parseObject(result, ForececastRiskCpuModel.class);
            }

        }catch (Exception e){
            LOGGER.error("getCpuRishTrends fail microSvcId={}",microSvcId,e);
        }

        return forececastRiskCpuModel;
    }

    @Override
    public void getAndSaveMicroSvcHistoryModel(String microSvcId) {
        String url =  algUrl + "/update_indicator";

        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("service_id",microSvcId);
        paramMap.put("calculate_type","cpu");

        //查询这个服务是cpu类型还是gpu类型的
        String busScence = microSvcMapper.getBusinessScenceBySvcId(microSvcId);
        if (StringUtils.contains(busScence,"AI训练")){
            paramMap.put("calculate_type","gpu");

        }

        String param = JSON.toJSONString(paramMap);
        try {

            String result = doHttpPostReq(url, new StringEntity(param));

            if (StringUtils.isNotEmpty(result)) {
                IndicatorAlgReturnModel indicatorAlgReturnModel
                        = JSONObject.parseObject(result, IndicatorAlgReturnModel.class);
                if (((Integer)indicatorAlgReturnModel.getCode()).equals(200)){

                    //处理保存
                    if (indicatorAlgReturnModel.getUpdate_value()!= null) {
                        IndicatorHistoryModel indicatorHistoryModel = new IndicatorHistoryModel();
                        indicatorHistoryModel.setMicroSvcId(microSvcId);

                        for (IndicatorAlgValueModel indicatorAlgValueModel:indicatorAlgReturnModel.getUpdate_value()){

                            switch (indicatorAlgValueModel.getIndicator_name()){
                                case "cpu_usage":
                                    indicatorHistoryModel.setCpuUsage(indicatorAlgValueModel.getValue());
                                    break;
                                case "memory_usage":
                                    indicatorHistoryModel.setMemUsage(indicatorAlgValueModel.getValue());
                                    break;
                                case "disk_iops":
                                    indicatorHistoryModel.setDiskIops(indicatorAlgValueModel.getValue());
                                    break;
                                case "disk_throughput":
                                    indicatorHistoryModel.setDiskThroughput(indicatorAlgValueModel.getValue());
                                    break;
                                case "net_bandwidth":
                                    indicatorHistoryModel.setNetBandwidth(indicatorAlgValueModel.getValue());
                                    break;
                            }
                        }

                        //保存
                        indicatorHistoryModel.setCreateTime(new Date());
                        microSvcUseInfoMapper.saveIndicatorHistoryModel(indicatorHistoryModel);
                    }
                }else {
                    throw new Exception("indicator return error msg=" + indicatorAlgReturnModel.getMsg());
                }
            }

        }catch (Exception e){

            LOGGER.error("getAndSaveMicroSvcHistoryModel fail microSvcId={}",microSvcId,e);
        }

    }


    /**
     *
     * @param url
     * @param param
     * @return
     */
    private String doHttpPostReq(String url, StringEntity param){

        try {

            CloseableHttpClient httpclient = HttpClients.createDefault();

            HttpPost httpPost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5 * 60 * 1000).setConnectionRequestTimeout(5 * 60 * 1000)
                    .setSocketTimeout(5 * 60 * 1000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(param);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());

        }catch (Throwable e){
            LOGGER.error("vmRes doHttpPostReq fail url={}",url,e);
        }

        return null;
    }

    @Override
    public MicroSvcReqCostInfoModel getMicroSvcReqCostLastHour(String microSvcId) {

        MicroSvcReqCostInfoModel result = new MicroSvcReqCostInfoModel();
        result.setMicroSvcId(microSvcId);

        Date time1hourBefore = new Date((new Date()).getTime() - 60 * 60 * 1000L);
        List<MicroSvcReqCostInfoModel> microSvcReqCostInfoModels
                = microSvcUseInfoMapper.getReqCostInfoByDate(microSvcId,time1hourBefore);
        if ((microSvcReqCostInfoModels != null)&&(!microSvcReqCostInfoModels.isEmpty())){
            int reqNum = 0;
            int reqTimeTotal = 0;
            for (;reqNum < microSvcReqCostInfoModels.size();reqNum++){
                reqTimeTotal += microSvcReqCostInfoModels.get(reqNum).getReqCost();
            }

            result.setReqCost(reqTimeTotal/reqNum);
        }


        return result;
    }

    @Override
    public MicroSvcDataSaveModel getMicroSvcDataNow(String k8sClusterName, String microSvcId) {

        LOGGER.warn("getMicroSvcDataNow k8sClusterName={} microSvcId={}",k8sClusterName,microSvcId);

        MicroSvcDataSaveModel result = new MicroSvcDataSaveModel();
        result.setK8sClusterName(k8sClusterName);
        result.setMicroSvcId(microSvcId);
        K8sClusterBasicModel k8sClusterBasicModel =
                cacheService.getK8sBasicModel(k8sClusterName);
        if (k8sClusterBasicModel == null) {
            k8sClusterBasicModel = multiCloudMgmtService.getK8sClusterInfoByName(k8sClusterName);
        }
        result.setCloudVendor(k8sClusterBasicModel.getCloudVendor());

        //找到这个svc最近一次记录的时间
        Date maxDate = microSvcUseInfoMapper.getSvcMaxDate(k8sClusterName,microSvcId);
        if (maxDate == null){
            return result;
        }

        List<MicroSvcDataSaveModel> microSvcDataSaveModels =
                microSvcUseInfoMapper.getMicroSvcUseInfoByClusterNameMicroSvcId(k8sClusterName,microSvcId,maxDate);
        if (microSvcDataSaveModels.isEmpty()){
            return result;
        }


        for (MicroSvcDataSaveModel microSvcDataSaveModel:microSvcDataSaveModels){

            result.setCpuUse(microSvcDataSaveModel.getCpuUse() + result.getCpuUse());
            result.setCpuTotal(microSvcDataSaveModel.getCpuTotal() + result.getCpuTotal());
            result.setMemUse(microSvcDataSaveModel.getMemUse() + result.getMemUse());
            result.setMemTotal(microSvcDataSaveModel.getMemTotal() + result.getMemTotal());
        }

        //如果是gpu，则增加温度查询
        if (StringUtils.containsIgnoreCase(k8sClusterBasicModel.getK8sClusterName(),CnapCloudMgmtConstants.ARCH_GPU)){
            result.setGpuTemp(prometheusService.getGpuTemp(k8sClusterBasicModel.getK8sClusterIp()));
        }

        return result;
    }

    /**
     * 获取12小时内的节点的数据,24个点，半小时一个点
     * @param nodeAlarmReqInfoModel
     * @return
     */
    @Override
    public AlarmNodeInfoModel getAlarmNodeInfo(NodeAlarmReqInfoModel nodeAlarmReqInfoModel) {

        AlarmNodeInfoModel alarmNodeInfoModel = new AlarmNodeInfoModel();
        alarmNodeInfoModel.setK8sClusterName(nodeAlarmReqInfoModel.getK8sClusterName());

        Date nowDate = new Date();
        Date time12HourAgo = new Date(nowDate.getTime() - 12 * 60 * 60 * 1000);

        for (String nodeName:nodeAlarmReqInfoModel.getNodeNames()){

            List<NodeHistoryInfoModel> nodeHistoryInfoModels =
                    microSvcUseInfoMapper.getNodeHistoryInfoModelsByDate(nodeName,
                            nodeAlarmReqInfoModel.getK8sClusterName(),time12HourAgo);

            //从12小时之前开始，到现在，先把所有的值填写为0，然后寻找在这个半小时内的点
            int i = 0;
            int nodeIndex = 0;
            while ((time12HourAgo.getTime() + (i * 30*60*1000)) < nowDate.getTime()) {


                Date timeToGet = new Date(time12HourAgo.getTime() + (i * 30*60*1000));
                if (alarmNodeInfoModel.getCpuUsage() == null) {
                    alarmNodeInfoModel.setCpuUsage(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getCpuUsage().size() <= i){
                    alarmNodeInfoModel.getCpuUsage().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getCpuUsage().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getCpuUsage().get(i).setRecords(new ArrayList<>());
                }

                if (alarmNodeInfoModel.getMemUsageList() == null){
                    alarmNodeInfoModel.setMemUsageList(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getMemUsageList().size() <= i){
                    alarmNodeInfoModel.getMemUsageList().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getMemUsageList().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getMemUsageList().get(i).setRecords(new ArrayList<>());

                }

                if (alarmNodeInfoModel.getGpuTemps() == null){
                    alarmNodeInfoModel.setGpuTemps(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getGpuTemps().size() <= i){
                    alarmNodeInfoModel.getGpuTemps().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getGpuTemps().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getGpuTemps().get(i).setRecords(new ArrayList<>());

                }

                if (alarmNodeInfoModel.getGpuUsageList() == null){
                    alarmNodeInfoModel.setGpuUsageList(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getGpuUsageList().size() <= i){
                    alarmNodeInfoModel.getGpuUsageList().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getGpuUsageList().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getGpuUsageList().get(i).setRecords(new ArrayList<>());

                }

                if (alarmNodeInfoModel.getDiskIopsList() == null){
                    alarmNodeInfoModel.setDiskIopsList(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getDiskIopsList().size() <= i){
                    alarmNodeInfoModel.getDiskIopsList().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getDiskIopsList().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getDiskIopsList().get(i).setRecords(new ArrayList<>());

                }

                if (alarmNodeInfoModel.getDiskThroughputList() == null){
                    alarmNodeInfoModel.setDiskThroughputList(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getDiskThroughputList().size() <= i){
                    alarmNodeInfoModel.getDiskThroughputList().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getDiskThroughputList().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getDiskThroughputList().get(i).setRecords(new ArrayList<>());
                }

                if (alarmNodeInfoModel.getGpuMemUsageList() == null){
                    alarmNodeInfoModel.setGpuMemUsageList(new ArrayList<>());
                }
                if (alarmNodeInfoModel.getGpuMemUsageList().size() <= i){
                    alarmNodeInfoModel.getGpuMemUsageList().add(new AlarmSvcDataModel());
                    alarmNodeInfoModel.getGpuMemUsageList().get(i).setRecordTime(timeToGet);
                    alarmNodeInfoModel.getGpuMemUsageList().get(i).setRecords(new ArrayList<>());
                }


                //如果就没查到数据，那就直接塞0
                if (nodeHistoryInfoModels.isEmpty()){
                    alarmNodeInfoModel.getCpuUsage().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                    alarmNodeInfoModel.getMemUsageList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                    alarmNodeInfoModel.getGpuTemps().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                    alarmNodeInfoModel.getGpuUsageList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                    alarmNodeInfoModel.getDiskThroughputList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                    alarmNodeInfoModel.getDiskIopsList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                    alarmNodeInfoModel.getGpuMemUsageList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,0));
                }else{

                    int cpuUsage = 0;
                    int memusage = 0;
                    int gpuUsage = 0;
                    int gpuTemp = 0;
                    int dataNum = 0;
                    int diskIops = 0;
                    int diskThroghput = 0;
                    int gpuMemUsage = 0;
                    //找到这30分钟内的所有数据，然后给他算个平均加入
                    for (;nodeIndex < nodeHistoryInfoModels.size();nodeIndex++){

                        //如果时间比初始时间+30分钟还要离现在近，那就不取数据了
                        if (nodeHistoryInfoModels.get(nodeIndex).getCreateDate().getTime() >
                                (timeToGet.getTime() + 30*60*1000)){
                            break;

                        }else {
                            //说明时间在获取范围内
                            dataNum++;
                            cpuUsage = cpuUsage +
                                    (int)(((double)nodeHistoryInfoModels.get(nodeIndex).getNodeCpuUseM()/
                                            nodeHistoryInfoModels.get(nodeIndex).getNodeCpuQuotaM()) * 100);
                            memusage = memusage +
                                    (int)(((double)nodeHistoryInfoModels.get(nodeIndex).getNodeMemUseKi()/
                                            nodeHistoryInfoModels.get(nodeIndex).getNodeMemQuotaKi()) * 100);
                            gpuTemp = gpuTemp + (int)nodeHistoryInfoModels.get(nodeIndex).getNodeGpuTemp();
                            gpuUsage = gpuUsage + (int)nodeHistoryInfoModels.get(nodeIndex).getNodeGpuUsage();

                            diskIops = diskIops + nodeHistoryInfoModels.get(nodeIndex).getDiskIops();
                            diskThroghput = diskThroghput + nodeHistoryInfoModels.get(nodeIndex).getDiskThroghput();
                            gpuMemUsage = gpuUsage + (int)(nodeHistoryInfoModels.get(nodeIndex).getNodeGpuMemUsage()*100);
                        }

                    }

                    if (dataNum != 0){
                        cpuUsage = cpuUsage/dataNum;
                        memusage = memusage/dataNum;
                        gpuUsage = gpuUsage/dataNum;
                        gpuTemp = gpuTemp/dataNum;
                        diskIops = diskIops/dataNum;
                        diskThroghput = diskThroghput/dataNum;
                        gpuMemUsage = gpuMemUsage/dataNum;
                    }

                    alarmNodeInfoModel.getCpuUsage().get(i).getRecords().add(
                            new SvcDataModel(nodeName,cpuUsage));
                    alarmNodeInfoModel.getMemUsageList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,memusage));
                    alarmNodeInfoModel.getGpuTemps().get(i).getRecords().add(
                            new SvcDataModel(nodeName,gpuTemp));
                    alarmNodeInfoModel.getGpuUsageList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,gpuUsage));

                    alarmNodeInfoModel.getDiskIopsList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,diskIops));
                    alarmNodeInfoModel.getDiskThroughputList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,diskThroghput));
                    alarmNodeInfoModel.getGpuMemUsageList().get(i).getRecords().add(
                            new SvcDataModel(nodeName,gpuMemUsage));

                }

                i++;
            }
        }

        return alarmNodeInfoModel;
    }

    @Override
    public AlarmSvcInfoModel getMicroSvcsInfo(String k8sClusterName, List<String> microSvcNames,String userName) {

        AlarmSvcInfoModel alarmSvcInfoModel = new AlarmSvcInfoModel();
        alarmSvcInfoModel.setK8sClusterName(k8sClusterName);
        List<AlarmSvcDataModel> cpuUsageList = new ArrayList<>();
        List<AlarmSvcDataModel> reqCostTimeList = new ArrayList<>();
        List<AlarmSvcDataModel> gpuTempList = new ArrayList<>();

        List<AlarmSvcDataModel> memUsageList = new ArrayList<>();
        List<AlarmSvcDataModel> diskIopsList = new ArrayList<>();
        List<AlarmSvcDataModel> diskThroughputList = new ArrayList<>();
        List<AlarmSvcDataModel> gpuUsageList = new ArrayList<>();
        List<AlarmSvcDataModel> gpuMemUsageList = new ArrayList<>();

        //获取数据，组装
        for (String microSvcName: microSvcNames){

            MicroSvcUseInfoModel microSvcUseInfoModel =
                    getMicroSvcUseInfo("","","",k8sClusterName,microSvcName,userName);
            if ((microSvcUseInfoModel.getCpuUseModels() == null)||
                    (microSvcUseInfoModel.getCpuUseModels().isEmpty())){
                continue;
            }

            //找到对应的DiskIops，放入数据
            for (int i = 0;i < microSvcUseInfoModel.getDiskThroughputList().size();i++){

                DiskThrouthputModel diskThrouthputModel = microSvcUseInfoModel.getDiskThroughputList().get(i);

                //说明还没填充过
                if (i >= diskThroughputList.size()){

                    AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                    alarmSvcDataModel.setRecordTime(diskThrouthputModel.getRecordTime());
                    alarmSvcDataModel.setRecords(new ArrayList<>());
                    SvcDataModel svcDataModel = new SvcDataModel();
                    svcDataModel.setMicroSvcName(microSvcName);
                    svcDataModel.setRecord(diskThrouthputModel.getDiskdiskThroughput());
                    alarmSvcDataModel.getRecords().add(svcDataModel);

                    diskThroughputList.add(alarmSvcDataModel);

                }else {

                    SvcDataModel svcDataModel = new SvcDataModel();
                    svcDataModel.setMicroSvcName(microSvcName);
                    svcDataModel.setRecord(diskThrouthputModel.getDiskdiskThroughput());
                    diskThroughputList.get(i).getRecords().add(svcDataModel);
                }
            }

            //找到对应的DiskIops，放入数据
            for (int i = 0;i < microSvcUseInfoModel.getDiskIopsList().size();i++){

                DiskIopsModel diskIopsModel = microSvcUseInfoModel.getDiskIopsList().get(i);

                //说明还没填充过
                if (i >= diskIopsList.size()){

                    AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                    alarmSvcDataModel.setRecordTime(diskIopsModel.getRecordTime());
                    alarmSvcDataModel.setRecords(new ArrayList<>());
                    SvcDataModel svcDataModel = new SvcDataModel();
                    svcDataModel.setMicroSvcName(microSvcName);
                    svcDataModel.setRecord(diskIopsModel.getDiskIops());
                    alarmSvcDataModel.getRecords().add(svcDataModel);

                    diskIopsList.add(alarmSvcDataModel);

                }else {

                    SvcDataModel svcDataModel = new SvcDataModel();
                    svcDataModel.setMicroSvcName(microSvcName);
                    svcDataModel.setRecord(diskIopsModel.getDiskIops());
                    diskIopsList.get(i).getRecords().add(svcDataModel);
                }
            }

            //找到对应的gpu mem，放入数据
            if (microSvcUseInfoModel.getGpuUseModels() != null) {
                for (int i = 0; i < microSvcUseInfoModel.getGpuUseModels().size(); i++) {

                    GpuUseModel gpuUseModel = microSvcUseInfoModel.getGpuUseModels().get(i);

                    //说明还没填充过
                    if (i >= gpuUsageList.size()) {

                        AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                        alarmSvcDataModel.setRecordTime(gpuUseModel.getRecordTime());
                        alarmSvcDataModel.setRecords(new ArrayList<>());
                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gpuUseModel.getGpuUsePercent());
                        alarmSvcDataModel.getRecords().add(svcDataModel);

                        gpuUsageList.add(alarmSvcDataModel);

                    } else {

                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gpuUseModel.getGpuUsePercent());
                        gpuUsageList.get(i).getRecords().add(svcDataModel);
                    }
                }
            }

            //找到对应的gpu mem，放入数据
            if (microSvcUseInfoModel.getGpuMemUseModels() != null) {
                for (int i = 0; i < microSvcUseInfoModel.getGpuMemUseModels().size(); i++) {

                    GpuMemUseModel gpuMemUseModel = microSvcUseInfoModel.getGpuMemUseModels().get(i);

                    //说明还没填充过
                    if (i >= gpuMemUsageList.size()) {

                        AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                        alarmSvcDataModel.setRecordTime(gpuMemUseModel.getRecordTime());
                        alarmSvcDataModel.setRecords(new ArrayList<>());
                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gpuMemUseModel.getGpuMemUsePercent());
                        alarmSvcDataModel.getRecords().add(svcDataModel);

                        gpuMemUsageList.add(alarmSvcDataModel);

                    } else {

                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gpuMemUseModel.getGpuMemUsePercent());
                        gpuMemUsageList.get(i).getRecords().add(svcDataModel);
                    }
                }
            }

            //找到对应的mem，放入数据
            if (microSvcUseInfoModel.getMemUseModels() != null) {
                for (int i = 0; i < microSvcUseInfoModel.getMemUseModels().size(); i++) {

                    MemUseModel memUseModel = microSvcUseInfoModel.getMemUseModels().get(i);

                    //说明还没填充过
                    if (i >= memUsageList.size()) {

                        AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                        alarmSvcDataModel.setRecordTime(memUseModel.getRecordTime());
                        alarmSvcDataModel.setRecords(new ArrayList<>());
                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(memUseModel.getMemUsePercent());
                        alarmSvcDataModel.getRecords().add(svcDataModel);

                        memUsageList.add(alarmSvcDataModel);

                    } else {

                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(memUseModel.getMemUsePercent());
                        memUsageList.get(i).getRecords().add(svcDataModel);
                    }
                }
            }

            //找到对应的cpuUsage，放入数据
            if(microSvcUseInfoModel.getCpuUseModels() != null) {
                for (int i = 0; i < microSvcUseInfoModel.getCpuUseModels().size(); i++) {

                    CpuUseModel cpuUseModel = microSvcUseInfoModel.getCpuUseModels().get(i);

                    //说明还没填充过
                    if (i >= cpuUsageList.size()) {

                        AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                        alarmSvcDataModel.setRecordTime(cpuUseModel.getRecordTime());
                        alarmSvcDataModel.setRecords(new ArrayList<>());
                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(cpuUseModel.getCpuUsePercent());
                        alarmSvcDataModel.getRecords().add(svcDataModel);

                        cpuUsageList.add(alarmSvcDataModel);

                    } else {

                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(cpuUseModel.getCpuUsePercent());
                        cpuUsageList.get(i).getRecords().add(svcDataModel);
                    }
                }
            }

            //组装请求时间
            if (microSvcUseInfoModel.getGatewayLogModels() != null) {
                for (int i = 0; i < microSvcUseInfoModel.getGatewayLogModels().size(); i++) {

                    GatewayLogModel gatewayLogModel = microSvcUseInfoModel.getGatewayLogModels().get(i);

                    if (i >= reqCostTimeList.size()) {

                        AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                        alarmSvcDataModel.setRecordTime(gatewayLogModel.getCreateTime());
                        alarmSvcDataModel.setRecords(new ArrayList<>());
                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gatewayLogModel.getReqCost());
                        alarmSvcDataModel.getRecords().add(svcDataModel);

                        reqCostTimeList.add(alarmSvcDataModel);


                    } else {

                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gatewayLogModel.getReqCost());
                        reqCostTimeList.get(i).getRecords().add(svcDataModel);

                    }
                }
            }

            if (microSvcUseInfoModel.getGpuTempUseModels() != null){
                //组装请求时间
                for (int i = 0;i < microSvcUseInfoModel.getGpuTempUseModels().size();i++){

                    GpuTempUseModel gpuTempUseModel = microSvcUseInfoModel.getGpuTempUseModels().get(i);

                    if (i >= gpuTempList.size()){

                        AlarmSvcDataModel alarmSvcDataModel = new AlarmSvcDataModel();
                        alarmSvcDataModel.setRecordTime(gpuTempUseModel.getRecordTime());
                        alarmSvcDataModel.setRecords(new ArrayList<>());
                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gpuTempUseModel.getGpuTemp());
                        alarmSvcDataModel.getRecords().add(svcDataModel);

                        gpuTempList.add(alarmSvcDataModel);

                    }else {

                        SvcDataModel svcDataModel = new SvcDataModel();
                        svcDataModel.setMicroSvcName(microSvcName);
                        svcDataModel.setRecord(gpuTempUseModel.getGpuTemp());
                        gpuTempList.get(i).getRecords().add(svcDataModel);

                    }
                }
            }
        }
        //时间组装完毕之后，按照name排序一下，这样固定顺序给前端
        if (!cpuUsageList.isEmpty()) {
            for (AlarmSvcDataModel alarmSvcDataModel : cpuUsageList) {
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }
        }
        //reg组装完毕之后，按照name排序一下，这样固定顺序给前端
        if (!reqCostTimeList.isEmpty()) {

            for (AlarmSvcDataModel alarmSvcDataModel : reqCostTimeList) {
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }
        }
        //memuse
        if (!memUsageList.isEmpty()) {
            for (AlarmSvcDataModel alarmSvcDataModel : memUsageList) {
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }
        }
        //diskIopsList
        if (!diskIopsList.isEmpty()) {
            for (AlarmSvcDataModel alarmSvcDataModel : diskIopsList) {
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }
        }
        //diskThroughputList
        if (!diskThroughputList.isEmpty()) {
            for (AlarmSvcDataModel alarmSvcDataModel : diskThroughputList) {
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }
        }

        if (!gpuTempList.isEmpty()){
            for (AlarmSvcDataModel alarmSvcDataModel :gpuTempList){
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }

            for (AlarmSvcDataModel  alarmSvcDataModel:gpuUsageList){
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }

            for (AlarmSvcDataModel  alarmSvcDataModel:gpuMemUsageList){
                alarmSvcDataModel.getRecords().sort(Comparator.comparing(SvcDataModel::getMicroSvcName));
            }
        }

        alarmSvcInfoModel.setDiskIopsList(diskIopsList);
        alarmSvcInfoModel.setReqCostTimes(reqCostTimeList);
        alarmSvcInfoModel.setCpuUsage(cpuUsageList);
        alarmSvcInfoModel.setGpuTemps(gpuTempList);
        alarmSvcInfoModel.setMemUsageList(memUsageList);
        alarmSvcInfoModel.setGpuUsageList(gpuUsageList);
        alarmSvcInfoModel.setGpuMemUsageList(gpuMemUsageList);
        alarmSvcInfoModel.setDiskThroughputList(diskThroughputList);

        return alarmSvcInfoModel;
    }

    /**
     * 获取最近5分钟使用情况
     * @param cloudVendor
     * @param regionId
     * @param zoneId
     * @param clusterName
     * @param microSvcName
     * @param userName
     * @return
     */
    @Override
    public MicroSvcUseInfoModel getMicroSvcUseInfo(String cloudVendor, String regionId, String zoneId, String clusterName, String microSvcName, String userName) {

        MicroSvcUseInfoModel microSvcUseInfoModel = new MicroSvcUseInfoModel();

        List<SvcModel> svcModels = getAllSvcModelForMicroSvc(cloudVendor,regionId,zoneId,clusterName,microSvcName,userName);
        if (svcModels.size() != 1){
            LOGGER.error("getMicroSvcUseInfo svcmodels size wrong size={} clusterName={} microSvcName={}",
                    svcModels.size(),clusterName,microSvcName);
            return microSvcUseInfoModel;
        }

        SvcModel svcModel = svcModels.get(0);

        microSvcUseInfoModel.setCloudVender(svcModel.getCloudVendor());
        microSvcUseInfoModel.setZoneId(svcModel.getZoneId());
        microSvcUseInfoModel.setRegionId(svcModel.getRegionId());
        microSvcUseInfoModel.setK8sClusterIp(svcModel.getK8sClusterIp());
        microSvcUseInfoModel.setK8sClusterName(svcModel.getK8sClusterName());

        //中间存在的没有耗时的，要补0
        microSvcUseInfoModel.setGatewayLogModels(new ArrayList<>());
        microSvcUseInfoModel.setCpuUseModels(new ArrayList<>());
        microSvcUseInfoModel.setMemUseModels(new ArrayList<>());
        //gpu应用
        if (StringUtils.equalsIgnoreCase(svcModel.getArch(),CnapCloudMgmtConstants.ARCH_GPU)){
            microSvcUseInfoModel.setGpuMemUseModels(new ArrayList<>());
            microSvcUseInfoModel.setGpuTempUseModels(new ArrayList<>());
            microSvcUseInfoModel.setGpuUseModels(new ArrayList<>());
        }

        microSvcUseInfoModel.setDiskIopsList(new ArrayList<>());
        microSvcUseInfoModel.setDiskThroughputList(new ArrayList<>());

            //为了找image等信息，先拿到podmodel相关的
        List<PodModel> podModels = cacheService.getK8sPodModels(userName,svcModel.getK8sClusterName());
        if (podModels == null){
            return microSvcUseInfoModel;
        }
        Map<String,PodModel> podNameModelMap = new HashMap<>();
        for (PodModel podModel:podModels){
            podNameModelMap.put(podModel.getPodName(),podModel);
        }

        //整理podName
        Set<String> podNameSet = new HashSet<>();
        Set<String> podNewNameSet = new HashSet<>();
        //整理image
        Set<String> imageNameSet = new HashSet<>();
        //从24小时前开始，获取数据，如果没有，就填写0;
        Date nowDate = new Date();
        long time24hourBefore = nowDate.getTime() - 24*60*60* 1000L;
        for (long i = time24hourBefore;i < nowDate.getTime();i += 60 * 60 * 1000L){

            //获取这个时间段后一个小时的情况
            List<MicroSvcDataSaveModel> microSvcDataSaveModels =
                    microSvcUseInfoMapper.getMicroSvcUseInfoByDateRange(svcModel.getK8sClusterIp(),microSvcName,
                            new Date(i),new Date(i + 60*60*1000L));
            //cpu数据
            CpuUseModel cpuUseModel = new CpuUseModel();
            cpuUseModel.setRecordTimestamp(i);
            //mem数据
            MemUseModel memUseModel = new MemUseModel();
            memUseModel.setRecordTimestamp(i);
            //平均的耗时
            GatewayLogModel gatewayLogModel = new GatewayLogModel();
            gatewayLogModel.setCreateTimestamp(i);
            //磁盘iops
            DiskIopsModel diskIopsModel = new DiskIopsModel();
            diskIopsModel.setRecordTimestamp(i);
            //磁盘吞吐
            DiskThrouthputModel diskThrouthputModel = new DiskThrouthputModel();
            diskThrouthputModel.setRecordTimestamp(i);

            //如果这个时间段是空，那就都记录成0
            if ((microSvcDataSaveModels == null)||(microSvcDataSaveModels.isEmpty())){

                cpuUseModel.setCpuUsePercent(0);
                microSvcUseInfoModel.getCpuUseModels().add(cpuUseModel);

                memUseModel.setMemUsePercent(0);
                microSvcUseInfoModel.getMemUseModels().add(memUseModel);

                gatewayLogModel.setReqCost(0);
                microSvcUseInfoModel.getGatewayLogModels().add(gatewayLogModel);

                diskIopsModel.setDiskIops(0);
                microSvcUseInfoModel.getDiskIopsList().add(diskIopsModel);

                diskThrouthputModel.setDiskdiskThroughput(0);
                microSvcUseInfoModel.getDiskThroughputList().add(diskThrouthputModel);


                //如果是gpu应用，那就要设置gpu相关
                if (StringUtils.equalsIgnoreCase(svcModel.getArch(),CnapCloudMgmtConstants.ARCH_GPU)){

                    GpuTempUseModel gpuTempUseModel = new GpuTempUseModel();
                    gpuTempUseModel.setRecordTimestamp(i);
                    gpuTempUseModel.setGpuTemp(0);
                    microSvcUseInfoModel.getGpuTempUseModels().add(gpuTempUseModel);

                    GpuMemUseModel gpuMemUseModel = new GpuMemUseModel();
                    gpuMemUseModel.setRecordTimestamp(i);
                    gpuMemUseModel.setGpuMemUsePercent(0);
                    microSvcUseInfoModel.getGpuMemUseModels().add(gpuMemUseModel);

                    GpuUseModel gpuUseModel = new GpuUseModel();
                    gpuUseModel.setRecordTimestamp(i);
                    gpuUseModel.setGpuUsePercent(0);
                    microSvcUseInfoModel.getGpuUseModels().add(gpuUseModel);

                }

                //继续下个时间点
                continue;
            }

            for (MicroSvcDataSaveModel microSvcDataSaveModel:microSvcDataSaveModels){

                //去重保存容器名称
                /**
                 * 一个微服务可能有多个pod用的，
                 * 所以要把同一个时间的同个微服务不同pod用的量加起来
                 */
                if (!podNameSet.contains(microSvcDataSaveModel.getPodName())){
                    podNameSet.add(microSvcDataSaveModel.getPodName());
                    //找找这个pod的image
                    PodModel podModel = podNameModelMap.get(microSvcDataSaveModel.getPodName());

                    if((podModel != null)
                            &&(podModel.getContainerModels() != null)
                            &&(!podModel.getContainerModels().isEmpty())){
                        for (ContainerModel containerModel:podModel.getContainerModels()){
                            imageNameSet.add(containerModel.getContainerImage());
                        }

                        podNewNameSet.add(podModel.getPodName());
                    }
                }

                //记录下这个时间段所有的pod的mem和 CPU相加，因为是需要使用率，所以不用做除法来获取平均
                cpuUseModel.setCpuUse(cpuUseModel.getCpuUse() + microSvcDataSaveModel.getCpuUse());
                memUseModel.setMemUse(memUseModel.getMemUse() + microSvcDataSaveModel.getMemUse());
                cpuUseModel.setCpuTotal(cpuUseModel.getCpuTotal() + microSvcDataSaveModel.getCpuTotal());
                memUseModel.setMemTotal(memUseModel.getMemTotal() + microSvcDataSaveModel.getMemTotal());


                diskIopsModel.setDiskIops(microSvcDataSaveModel.getDiskIops() + diskIopsModel.getDiskIops());
                diskThrouthputModel.setDiskdiskThroughput(microSvcDataSaveModel.getDiskThroughput()
                        + diskThrouthputModel.getDiskdiskThroughput());
            }


            microSvcUseInfoModel.getCpuUseModels().add(cpuUseModel);
            microSvcUseInfoModel.getMemUseModels().add(memUseModel);

            diskIopsModel.setDiskIops(diskIopsModel.getDiskIops()/microSvcDataSaveModels.size());
            microSvcUseInfoModel.getDiskIopsList().add(diskIopsModel);

            diskThrouthputModel.setDiskdiskThroughput(diskThrouthputModel.getDiskdiskThroughput()
                    /microSvcDataSaveModels.size());
            microSvcUseInfoModel.getDiskThroughputList().add(diskThrouthputModel);

            //如果是gpu应用，那就要设置gpu相关
            if (StringUtils.equalsIgnoreCase(svcModel.getArch(),CnapCloudMgmtConstants.ARCH_GPU)){

                GpuTempUseModel gpuTempUseModel = new GpuTempUseModel();
                GpuMemUseModel gpuMemUseModel = new GpuMemUseModel();
                GpuUseModel gpuUseModel = new GpuUseModel();

                for (MicroSvcDataSaveModel microSvcDataSaveModel:microSvcDataSaveModels) {

                    gpuTempUseModel.setRecordTimestamp(i);
                    gpuTempUseModel.setGpuTemp((int)(gpuTempUseModel.getGpuTemp()
                            + microSvcDataSaveModel.getGpuTemp()));

                    gpuMemUseModel.setRecordTimestamp(i);
                    gpuMemUseModel.setGpuMemUsePercent((int)(gpuMemUseModel.getGpuMemUsePercent()
                        + microSvcDataSaveModel.getGpuMemUsage()*100));

                    gpuUseModel.setRecordTimestamp(i);
                    gpuUseModel.setGpuUsePercent((int)(gpuUseModel.getGpuUsePercent() +
                            microSvcDataSaveModel.getGpuUsage()));
                }

                gpuTempUseModel.setGpuTemp(gpuTempUseModel.getGpuTemp()/microSvcDataSaveModels.size());
                microSvcUseInfoModel.getGpuTempUseModels().add(gpuTempUseModel);

                gpuMemUseModel.setGpuMemUsePercent(
                        gpuMemUseModel.getGpuMemUsePercent()/microSvcDataSaveModels.size());
                microSvcUseInfoModel.getGpuMemUseModels().add(gpuMemUseModel);

                gpuUseModel.setGpuUsePercent(gpuUseModel.getGpuUsePercent()/microSvcDataSaveModels.size());
                microSvcUseInfoModel.getGpuUseModels().add(gpuUseModel);

            }


            //获取耗时
            List<MicroSvcReqCostInfoModel> microSvcReqCostInfoModels =
                    microSvcUseInfoMapper.getReqCostInfoByDateRange(svcModel.getMicroServicePO().getId(),
                            new Date(i),new Date(i + 60*60*1000L));
            if (microSvcDataSaveModels.isEmpty()){
                gatewayLogModel.setReqCost(0);
                microSvcUseInfoModel.getGatewayLogModels().add(gatewayLogModel);

                //继续下个时间点
                continue;
            }

            for (MicroSvcReqCostInfoModel costInfo:microSvcReqCostInfoModels){

                gatewayLogModel.setReqCost(costInfo.getReqCost() + gatewayLogModel.getReqCost());
            }

            gatewayLogModel.setReqCost(gatewayLogModel.getReqCost()/microSvcDataSaveModels.size());
            microSvcUseInfoModel.getGatewayLogModels().add(gatewayLogModel);

        }
        //保存镜像和pod名字
        microSvcUseInfoModel.setPodNames(new ArrayList<>(podNewNameSet));
        microSvcUseInfoModel.setImages(new ArrayList<>(imageNameSet));

        return microSvcUseInfoModel;
    }

    @Override
    public List<SvcModel> getAllSvcModelForMicroSvc(String cloudVendor, String regionId, String zoneId, String clusterName, String microSvcName, String userName) {

        List<SvcModel> result = new ArrayList<>();
        List<SvcModel> svcModels = cacheService.getSvcModelsForMicroSvc();
        if (!svcModels.isEmpty()){

            for (SvcModel svcModel:svcModels){

                if (StringUtils.isNotEmpty(userName)) {
                    if (!StringUtils.equals(svcModel.getCreateUser(), userName)) {
                        continue;
                    }
                }

                if (StringUtils.isNotEmpty(cloudVendor)){
                    if (!StringUtils.containsIgnoreCase(svcModel.getCloudVendor(),cloudVendor)){
                        continue;
                    }
                }

                if (StringUtils.isNotEmpty(regionId)){
                    if (!StringUtils.containsIgnoreCase(svcModel.getRegionId(),regionId)){
                        continue;
                    }
                }

                if (StringUtils.isNotEmpty(zoneId)){
                    if (!StringUtils.containsIgnoreCase(svcModel.getZoneId(),zoneId)){
                        continue;
                    }
                }

                if (StringUtils.isNotEmpty(clusterName)){
                    if (!StringUtils.containsIgnoreCase(svcModel.getK8sClusterName(),clusterName)){
                        continue;
                    }
                }

                if (StringUtils.isNotEmpty(microSvcName)){
                    if (!StringUtils.containsIgnoreCase(svcModel.getMicroServiceName(),microSvcName)){
                        continue;
                    }
                }

                result.add(svcModel);
            }
        }
        return result;
    }

    @Override
    public List<ClusterMicroSvcModel> getClusterMicroSvcInfos(String cloudVendor, String regionId,
                                                              String zoneId, String clusterName, String microSvcName, String userName) {

        List<ClusterMicroSvcModel> result = new ArrayList<>();

        List<SvcModel> svcModels = getAllSvcModelForMicroSvc(cloudVendor,regionId,
                zoneId,clusterName,microSvcName,userName);

        //安集群获取
        Map<String,ClusterMicroSvcModel> clusterMicroSvcModelMap = new HashMap<>();
        if (!svcModels.isEmpty()){

            for (SvcModel svcModel:svcModels){

                ClusterMicroSvcModel clusterMicroSvcModel = null;

                if (clusterMicroSvcModelMap.containsKey(svcModel.getK8sClusterIp())){

                    clusterMicroSvcModel = clusterMicroSvcModelMap.get(svcModel.getK8sClusterIp());

                }else {
                    clusterMicroSvcModel = new ClusterMicroSvcModel();
                    clusterMicroSvcModel.setCloudVendor(svcModel.getCloudVendor());
                    clusterMicroSvcModel.setK8sClusterIp(svcModel.getK8sClusterIp());
                    clusterMicroSvcModel.setK8sClusterName(svcModel.getK8sClusterName());
                    clusterMicroSvcModel.setRegionId(svcModel.getRegionId());
                    clusterMicroSvcModel.setZoneId(svcModel.getZoneId());
                    //处理nodemodels
                    RepByPage<NodeModel> nodeModelRepByPage =
                            cacheService.getK8sNodeInfoByClusterName(svcModel.getCreateUser(),svcModel.getK8sClusterName());
                    clusterMicroSvcModel.setNodeModels(nodeModelRepByPage.getResult());

                    clusterMicroSvcModel.setSvcModels(new ArrayList<>());

                    clusterMicroSvcModelMap.put(svcModel.getK8sClusterIp(),clusterMicroSvcModel);
                }

                //查查svc现在的告警情况
                List<String> alarms = alarmMapper.getSvcAlarmBySvcIdClusterName(svcModel.getMicroSvcId(),
                        svcModel.getK8sClusterName());
                //显示最高等级的告警
                svcModel.setSvcAlarm(AlarmLevelEnum.getMostOrderAlarmStr(alarms));

                clusterMicroSvcModel.getSvcModels().add(svcModel);

                result.add(clusterMicroSvcModel);
            }
        }

        return result;
    }

    @Override
    public List<String> getAllmicroSvcName(String cloudVendor,String regionId,String zoneId,String clusterName,
                                           String microSvcName,String userName) {

        List<String> result = new ArrayList<>();

        List<SvcModel> svcModels = getAllSvcModelForMicroSvc(cloudVendor,regionId,
                zoneId,clusterName,microSvcName,userName);
        if (!svcModels.isEmpty()){

            for (SvcModel svcModel:svcModels){
                result.add(svcModel.getMicroServiceName());
            }
        }

        return result;
    }

    @Override
    public NodeQueryModel queryResInfo(NodeQueryModel nodeQueryModel) throws Exception {

        Date queryDate = new Date((new Date()).getTime() - 1000 * 60 * nodeQueryModel.getQueryMinutes());

            //从clustername拿到username
            K8sClusterBasicModel k8sClusterBasicModel = multiCloudMgmtService
                    .getK8sClusterInfoByName(nodeQueryModel.getK8sClusterName());
            nodeQueryModel.setCloudVendor(k8sClusterBasicModel.getCloudVendor());

            String userName = k8sClusterBasicModel.getCreateUser();
            //通过resName查到这个svc的名称
            String svcName = nodeQueryModel.getNodeName();
            if (StringUtils.isEmpty(svcName)){
                svcName = nodeQueryModel.getName();
            }
            MicroServicePO microServicePO =
                    microSvcMapper.getMicroServiceByUserNameSvcName(
                            userName, svcName,nodeQueryModel.getSvcId());

            //获取他最近的使用情况
            AlgReqModel algReqModel = new AlgReqModel();
            algReqModel.setUserName(userName);
            algReqModel.setK8sClusterNames(new ArrayList<>());
            algReqModel.getK8sClusterNames().add(nodeQueryModel.getK8sClusterName());
            algReqModel.setSvcName(microServicePO.getServiceName());
            List<K8sClusterAlgInfoModel> k8sClusterAlgInfoModels = algInfoService.getHpaAlgInfo(algReqModel);
            List<DynamicExpansionSvcAlgModel> DynamicExpansionSvcAlgModels = algInfoService.getDynamicExpansionAlgInfo(algReqModel);
            //因为只有一个，所以只获取第一个的情况
            DynamicExpansionSvcAlgModel dynamicExpansionSvcAlgModel = DynamicExpansionSvcAlgModels.get(0);
            K8sClusterAlgInfoModel k8sClusterAlgInfoModel = k8sClusterAlgInfoModels.get(0);

            if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "内存使用率")) {

                //获取当前值
                int recentResult = dynamicExpansionSvcAlgModel.getSvcMemUse() / dynamicExpansionSvcAlgModel.getSvcMemLimit() * 100;

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper.getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                            microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算内存使用率
                            int tmpResult = microSvcDataSaveModel.getMemPercent();
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }
                }

            } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "磁盘吞吐率")) {

                //获取当前值
                int recentResult = k8sClusterAlgInfoModel.getClusterDiskUseByGb() / k8sClusterAlgInfoModel.getClusterDiskQuotaByGb();
                //todo 因为磁盘值没有记录，现在先返回当前值
                nodeQueryModel.setQueryResult(recentResult);

            } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "cpu使用率")) {

                //获取当前值
                int recentResult = (int) (dynamicExpansionSvcAlgModel.getSvcCpuUse() / dynamicExpansionSvcAlgModel.getSvcCpuLimit() * 100);

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper
                            .getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                                    microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算cpu
                            int tmpResult = microSvcDataSaveModel.getCpuPercent();
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }
                }

            } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "磁盘吞吐量")) {

                //获取当前值
                int recentResult = 0;
                for (NodeModel nodeModel : k8sClusterAlgInfoModel.getNodeModels()) {
                    recentResult = nodeModel.getDiskThroughput();
                }
                recentResult = recentResult / k8sClusterAlgInfoModel.getNodeModels().size();

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper
                            .getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                                    microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算cpu
                            int tmpResult = microSvcDataSaveModel.getDiskThroughput();
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }
                }

            } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "请求响应时间")) {


                List<MicroSvcReqCostInfoModel> microSvcReqCostInfoModels =
                        microSvcUseInfoMapper.getReqCostInfoByDate(microServicePO.getId(), queryDate);
                int maxResult = 0;
                int minResult = Integer.MAX_VALUE;
                int avgResult = 0;
                if (!microSvcReqCostInfoModels.isEmpty()) {
                    for (MicroSvcReqCostInfoModel microSvcReqCostInfoModel : microSvcReqCostInfoModels) {
                        if (microSvcReqCostInfoModel.getReqCost() > maxResult) {
                            maxResult = microSvcReqCostInfoModel.getReqCost();
                        }
                        if (microSvcReqCostInfoModel.getReqCost() < minResult) {
                            minResult = microSvcReqCostInfoModel.getReqCost();
                        }
                        avgResult = avgResult + microSvcReqCostInfoModel.getReqCost();
                    }
                    avgResult = avgResult / microSvcReqCostInfoModels.size();
                }

                if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                    nodeQueryModel.setQueryResult(maxResult);
                } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                    //防止最小值一直没赋值
                    if (minResult == Integer.MAX_VALUE) {
                        minResult = 0;
                    }
                    nodeQueryModel.setQueryResult(minResult);
                } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                    nodeQueryModel.setQueryResult(avgResult);
                }


            } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "磁盘IOPS")) {

                //获取当前值
                int recentResult = 0;
                for (NodeModel nodeModel : k8sClusterAlgInfoModel.getNodeModels()) {
                    recentResult = nodeModel.getDiskIops();
                }
                recentResult = recentResult / k8sClusterAlgInfoModel.getNodeModels().size();

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper
                            .getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                                    microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算cpu
                            int tmpResult = microSvcDataSaveModel.getDiskIops();
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }
                }
            }else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "显存使用率")) {

                //获取当前值
                int recentResult = 0;

                recentResult = (int)(k8sClusterAlgInfoModel.getGpuMemUsage()*100);

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper
                            .getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                                    microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算cpu
                            int tmpResult = (int)(microSvcDataSaveModel.getGpuMemUsage()*100);
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }
                }


            }else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "GPU使用率")){
                //获取当前值
                int recentResult = 0;

                recentResult = (int)(k8sClusterAlgInfoModel.getGpuUsage()*100);

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper
                            .getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                                    microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算cpu
                            int tmpResult = (int)(microSvcDataSaveModel.getGpuUsage()*100);
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }
                }

            }else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getIndicator(), "显卡温度")) {

                //获取当前值
                int recentResult = 0;

                recentResult = (int) (k8sClusterAlgInfoModel.getGpuTemp());

                //根据查询时间算，如果小于5，不管什么，都只返回当前值
                if (nodeQueryModel.getQueryMinutes() < 5) {

                    nodeQueryModel.setQueryResult(recentResult);
                } else {

                    //如果时间大于5，那就查查历史数据
                    List<MicroSvcDataSaveModel> microSvcDataSaveModels = microSvcUseInfoMapper
                            .getMicroSvcUseInfoByDate(k8sClusterBasicModel.getK8sClusterIp(),
                                    microServicePO.getMicroServiceName(), queryDate);
                    if (microSvcDataSaveModels.isEmpty()) {
                        nodeQueryModel.setQueryResult(recentResult);
                    } else {

                        int maxResult = recentResult;
                        int minResult = recentResult;
                        int avgResult = recentResult;
                        for (MicroSvcDataSaveModel microSvcDataSaveModel : microSvcDataSaveModels) {
                            //计算cpu
                            int tmpResult = (int) (microSvcDataSaveModel.getGpuUsage() * 100);
                            if (tmpResult > maxResult) {
                                maxResult = tmpResult;
                            }
                            if (tmpResult < minResult) {
                                minResult = tmpResult;
                            }
                            avgResult = avgResult + tmpResult;
                        }
                        avgResult = avgResult / (microSvcDataSaveModels.size() + 1);
                        if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最大值")) {
                            nodeQueryModel.setQueryResult(maxResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "最小值")) {
                            nodeQueryModel.setQueryResult(minResult);
                        } else if (StringUtils.equalsIgnoreCase(nodeQueryModel.getQueryType(), "平均值")) {
                            nodeQueryModel.setQueryResult(avgResult);
                        }
                    }

                }
            }

        return nodeQueryModel;
    }

    @Override
    public MicroSvcGpuInfoModel queryGpuHeat(MicroSvcGpuInfoModel microSvcGpuInfoModel) {

        K8sClusterBasicModel k8sClusterBasicModel =
                multiCloudMgmtService.getK8sClusterInfoByName(microSvcGpuInfoModel.getK8sClusterName());
        microSvcGpuInfoModel.setCloudVendor(k8sClusterBasicModel.getCloudVendor());
        if (StringUtils.containsIgnoreCase(k8sClusterBasicModel.getK8sClusterName(),CnapCloudMgmtConstants.ARCH_GPU)){
            microSvcGpuInfoModel.setGpuHeat(prometheusService.getGpuTemp(k8sClusterBasicModel.getK8sClusterIp()));
        }

        return microSvcGpuInfoModel;
    }

    @Override
    public void delIndictorHistory(String svcId) {
        microSvcUseInfoMapper.delIndictorHistoryBySvcId(svcId);
    }
}
